import requests
import sys
import io

# 修复中文输入问题
sys.stdin = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')

url = "https://spark-api-open.xf-yun.com/v1/chat/completions"
api_password = "nqPDCCdCKXnCaKEMYNOa:NVLFDIUhkAJRPVPJZDYY"  # 替换为你的凭证

# 初始化对话历史
conversation_history = []

while True:
    try:
        # 获取用户输入（显式指定utf-8编码）
        user_input = input("\n请输入您的问题(输入q退出): ").strip()

        if user_input.lower() == 'q':
            print("对话结束")
            break

        if not user_input:
            print("输入不能为空")
            continue

        # 添加当前问题到对话历史
        conversation_history.append({"role": "user", "content": user_input})

        # 构造请求数据
        data = {
            "model": "lite",
            "messages": conversation_history,
            "stream": False
        }

        headers = {
            "Authorization": f"Bearer {api_password}",
            "Content-Type": "application/json"
        }

        # 发送请求
        response = requests.post(url, headers=headers, json=data)
        response.raise_for_status()

        result = response.json()
        ai_reply = result["choices"][0]["message"]["content"]

        # 添加AI回复到对话历史
        conversation_history.append({"role": "assistant", "content": ai_reply})

        # 打印AI回复（确保使用支持中文的打印）
        print("\nAI回复:", ai_reply)

    except requests.exceptions.RequestException as e:
        print(f"请求出错: {str(e)}")
    except UnicodeDecodeError:
        print("编码错误：请确保终端支持UTF-8编码")
    except Exception as e:
        print(f"发生错误: {str(e)}")


        # 添加AI回复到对话历史
        conversation_history.append({"role": "assistant", "content": ai_reply})

        # 打印AI回复
        print("\nAI回复:", ai_reply)

    except requests.exceptions.RequestException as e:
        print(f"请求出错: {str(e)}")
    except KeyError:
        print("解析响应出错，请检查API返回格式")
    except Exception as e:
        print(f"发生未知错误: {str(e)}")